import React, { useEffect, useState } from 'react';
import { Form } from 'antd';
import { Button, InputItem, Toast } from 'antd-mobile';
import { SendCode, Icon } from '@/components';
import { setUerInfo, Role } from '@/common/index';
import { connect,useHistory } from 'umi';
import { TOKENKEY } from '@/common/const';
import { loginByCode,userLogin,fetchUserService } from '@/services/user';
import { regMap, storage,LOCALSTATE } from '@/utils';
import logo from '@/assets/images/logo.png';
import Cookies from 'js-cookie'
import style from './index.less';

const Index = (props) => {
  const [secondActived, setSecondActived] = useState(false);
  const [buttonDisabled, setButtonDisabled] = useState(true);
  const [form] = Form.useForm();
  const [type] = useState(1)
  const [hasLocal,setLocal] = useState(false)
  const history = useHistory();
  /**
   * 登录页面初始化,
   * 清除所有登录信息
   */
  useEffect(() => {
    const SESSION = storage.get('SESSION',true)
    if(SESSION){
      fetchUser()
    }
    setLocal(!!SESSION)
    storage.remove(TOKENKEY);
    storage.remove('hr-user');
  }, []);

  // 登录
  const login = async () => {
    try {
      const data = await form.validateFields();
      data.remember=false
      const loginResponse = await userLogin(data);
      if (loginResponse.code === 1) {
        
        const SESSION = Cookies.get('SESSION')
        if(SESSION){
          storage.set('SESSION',SESSION,true)
        }
        fetchUser()
        
        
      }
    } catch (error) {
      console.log(error);
    }
  };
  const fetchUser = async()=>{
    const res = await fetchUserService()
    if(res?.code===1){
      storage.set(LOCALSTATE,res.response,true)
      if(hasLocal){
        window.location.href='/home'
      }else {
        Toast.success('登录成功', 1.5, () => window.location.href='/home');
      }
      
    }
  }

  const validData = () => {
    const { userName, password } = form.getFieldsValue();
    if (userName && password) {
      setButtonDisabled(false);
    }
  };

  return (
    <div className={`${style.page} page`}>
      
      {/* <img src={logo} alt="logo" className={style.logo} /> */}
      {!hasLocal&&<Form form={form}>
        {type===1&&<>
          <div className={style.itemWrapper}>
          <Form.Item
            name="userName"
            validateFirst
            rules={[
              { required: true, message: '请输入用户名' },
            ]}
            className={style.item}
          >
            <InputItem
              placeholder="请输入用户名"
              maxLength={11}
              className={style.input}
              onChange={validData}
            ><Icon type="icon-icon1" /></InputItem>
          </Form.Item>
          
        </div>
        <div className={style.itemWrapper}>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
            className={style.item}
          >
            <InputItem
              type="password"
              placeholder="请输入密码"
              className={style.input}
              onChange={validData}
            ><Icon type="icon-password" /></InputItem>
          </Form.Item>
        </div>
        </>}
        {type===2&&<>
          <div className={style.itemWrapper}>
          <Form.Item
            name="mobile"
            validateFirst
            rules={[
              { required: true, message: '请输入手机号码' },
              { pattern: regMap.mobile, message: '请输入手机号码' },
            ]}
            className={style.item}
          >
            <InputItem
              placeholder="请输入手机号码"
              type="number"
              maxLength={11}
              className={style.input}
              onChange={validData}
              pattern="\d*"
            />
          </Form.Item>
          <SendCode
            classNames={style.sendCode}
            url={`/sms/sendCode`}
            payload={() => {
              return { mobile: form.getFieldValue('mobile'), businessKey: 'login' };
            }}
            active={secondActived}
          />
        </div>
        <div className={style.itemWrapper}>
          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码' }]}
            className={style.item}
          >
            <InputItem
              type="number"
              placeholder="请输入验证码"
              maxLength={6}
              className={style.input}
              onChange={validData}
            />
          </Form.Item>
        </div>
        </>}
        
        <Button type="primary" className={style.submit} onClick={login} disabled={buttonDisabled}>
          立即登录
        </Button>
      </Form>}
    </div>
  );
};
export default connect(({ user, loading }: any) => ({
  loading: loading.effects['user/fetchCurrent'],
  currentUser: user.currentUser,
}))(Index);
